class SnakeGame {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.ws = null;
        this.playerId = null;
        this.playerName = null;
        this.gameState = {
            players: [],
            foods: [],
            powerUps: [],
            leaderboard: []
        };
        
        this.keys = {};
        this.lastDirection = { x: 1, y: 0 };
        this.isMobile = this.detectMobile();
        this.touchStartX = 0;
        this.touchStartY = 0;
        this.selectedAvatar = 0;
        this.gameStartTime = null;
        
        this.GRID_SIZE = 20;
        
        // 加载背景图片
        this.backgroundImage = new Image();
        this.backgroundImage.src = 'images/bg.png';
        this.backgroundImageLoaded = false;
        this.backgroundImage.onload = () => {
            this.backgroundImageLoaded = true;
        };
        
        // 自适应画布尺寸
        this.updateCanvasSize();
        
        // 大地图系统 - 世界尺寸是画布的3倍
        this.WORLD_WIDTH = this.CANVAS_WIDTH * 3;
        this.WORLD_HEIGHT = this.CANVAS_HEIGHT * 3;
        
        // 摄像头系统
        this.camera = {
            x: 0,
            y: 0,
            targetX: 0,
            targetY: 0,
            smoothing: 0.8 // 摄像头跟随的平滑度，增加到0.8以获得更快的跟随
        };
        
        this.initializeUI();
        this.setupEventListeners();
        this.setupTouchControls();
        this.adjustCanvasForMobile();
        this.setupOrientationHandling();
        this.setupFullscreenControls();
    }
    
    detectMobile() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 768;
    }
    
    updateCanvasSize() {
        // 获取窗口尺寸
        const windowWidth = window.innerWidth;
        const windowHeight = window.innerHeight;
        
        // 画布始终铺满全屏
        let canvasWidth = windowWidth;
        let canvasHeight = windowHeight;
        
        // 优先最大化尺寸，然后调整到网格对齐
        this.CANVAS_WIDTH = Math.floor(canvasWidth / this.GRID_SIZE) * this.GRID_SIZE;
        this.CANVAS_HEIGHT = Math.floor(canvasHeight / this.GRID_SIZE) * this.GRID_SIZE;
        
        // 如果调整后的尺寸与原尺寸差距太大，则使用原尺寸
        if (canvasWidth - this.CANVAS_WIDTH > this.GRID_SIZE || 
            canvasHeight - this.CANVAS_HEIGHT > this.GRID_SIZE) {
            this.CANVAS_WIDTH = canvasWidth;
            this.CANVAS_HEIGHT = canvasHeight;
        }
        
        // 确保最小尺寸
        this.CANVAS_WIDTH = Math.max(this.CANVAS_WIDTH, this.GRID_SIZE * 20);
        this.CANVAS_HEIGHT = Math.max(this.CANVAS_HEIGHT, this.GRID_SIZE * 15);
        
        // 更新画布元素尺寸 - 消除白边的完整设置
        if (this.canvas) {
            this.canvas.width = this.CANVAS_WIDTH;
            this.canvas.height = this.CANVAS_HEIGHT;
            // PC端全屏设置，消除白边
            this.canvas.style.width = '100vw';
            this.canvas.style.height = '100vh';
            this.canvas.style.position = 'fixed';
            this.canvas.style.top = '0';
            this.canvas.style.left = '0';
            this.canvas.style.margin = '0';
            this.canvas.style.padding = '0';
            this.canvas.style.border = 'none';
            this.canvas.style.outline = 'none';
            this.canvas.style.objectFit = 'cover';
            this.canvas.style.objectPosition = 'center';
        }
        
        // 更新世界尺寸
        if (this.WORLD_WIDTH && this.WORLD_HEIGHT) {
            this.WORLD_WIDTH = this.CANVAS_WIDTH * 3;
            this.WORLD_HEIGHT = this.CANVAS_HEIGHT * 3;
        }
        
        // 如果已连接到服务器，发送新的画布尺寸
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify({
                type: 'updateCanvasSize',
                canvasWidth: this.CANVAS_WIDTH,
                canvasHeight: this.CANVAS_HEIGHT
            }));
        }
    }
    
    initializeUI() {
        // 获取UI元素
        this.elements = {
            playerSetupScreen: document.querySelector('.player-setup-screen'),
            gameContainer: document.querySelector('.game-container'),
            deathScreen: document.querySelector('.death-screen'),
            gameOverlay: document.querySelector('.game-overlay'),
            nameInput: document.getElementById('nameInput'),
            startButton: document.getElementById('startButton'),
            respawnButton: document.getElementById('respawnButton'),
            backButton: document.getElementById('backButton'),
            playerName: document.getElementById('playerName'),
            playerScore: document.getElementById('playerScore'),
            playerLength: document.getElementById('playerLength'),
            connectionStatus: document.getElementById('connectionStatus'),
            leaderboardList: document.getElementById('leaderboardList'),
            onlineCount: document.getElementById('onlineCount'),
            foodCount: document.getElementById('foodCount'),
            randomNameBtn: document.getElementById('randomNameBtn'),
            powerUpCount: document.getElementById('powerUpCount'),
            finalScore: document.getElementById('finalScore'),
            finalLength: document.getElementById('finalLength'),
            topMessageNotification: document.getElementById('topMessageNotification'),
            topMessageContent: document.getElementById('topMessageContent')
        };
        
        // 世界消息相关
        this.worldMessages = [];
        this.maxWorldMessages = 10;
        
        // 初始显示玩家设置页面
        this.showPlayerSetup();
    }
    
    setupEventListeners() {
        // 开始游戏按钮
        const startGame = () => {
            const name = this.elements.nameInput.value.trim();
            if (name) {
                // 连接到服务器
                this.connectToServer(name);
                
                // 隐藏玩家设置页面，显示游戏界面
                this.hidePlayerSetup();
                this.showGameInterface();
                
                console.log('游戏开始，玩家：', name);
            } else {
                alert('请输入昵称!');
            }
        };
        
        this.elements.startButton.addEventListener('click', startGame);
        this.elements.startButton.addEventListener('touchend', (e) => {
            e.preventDefault();
            startGame();
        });
        
        // 重生按钮
        const respawnGame = () => {
            this.respawn();
        };
        
        if (this.elements.respawnButton) {
            this.elements.respawnButton.addEventListener('click', respawnGame);
            this.elements.respawnButton.addEventListener('touchend', (e) => {
                e.preventDefault();
                respawnGame();
            });
        }
        
        // 返回设置按钮
        const backToSetup = () => {
            this.backToSetup();
        };
        
        if (this.elements.backButton) {
            this.elements.backButton.addEventListener('click', backToSetup);
            this.elements.backButton.addEventListener('touchend', (e) => {
                e.preventDefault();
                backToSetup();
            });
        }
        
        // 角色选择事件
        document.querySelectorAll('.avatar-option').forEach(option => {
            const selectAvatar = () => {
                document.querySelectorAll('.avatar-option').forEach(opt => opt.classList.remove('selected'));
                option.classList.add('selected');
                this.selectedAvatar = parseInt(option.dataset.avatar);
            };
            
            option.addEventListener('click', selectAvatar);
            option.addEventListener('touchend', (e) => {
                e.preventDefault();
                selectAvatar();
            });
        });
        
        // 随机名字生成
        const generateName = () => {
            this.generateRandomName();
        };
        
        this.elements.randomNameBtn.addEventListener('click', generateName);
        this.elements.randomNameBtn.addEventListener('touchend', (e) => {
            e.preventDefault();
            generateName();
        });
        
        // 回车键开始游戏
        this.elements.nameInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.elements.startButton.click();
            }
        });
        
        // 键盘控制（仅桌面端）
        if (!this.isMobile) {
            document.addEventListener('keydown', (e) => {
                // ESC键退出全屏
                if (e.key === 'Escape') {
                    if (document.fullscreenElement || 
                        document.webkitFullscreenElement || 
                        document.mozFullScreenElement || 
                        document.msFullscreenElement) {
                        if (document.exitFullscreen) {
                            document.exitFullscreen();
                        } else if (document.webkitExitFullscreen) {
                            document.webkitExitFullscreen();
                        } else if (document.mozCancelFullScreen) {
                            document.mozCancelFullScreen();
                        } else if (document.msExitFullscreen) {
                            document.msExitFullscreen();
                        }
                    }
                    return;
                }
                
                this.keys[e.key] = true;
                this.handleKeyPress(e.key);
            });
            
            document.addEventListener('keyup', (e) => {
                this.keys[e.key] = false;
            });
            
            // 防止方向键滚动页面
            document.addEventListener('keydown', (e) => {
                if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' '].includes(e.key)) {
                    e.preventDefault();
                }
            });
        }
        
        // 窗口大小变化时调整画布
        window.addEventListener('resize', () => {
            this.adjustCanvasForMobile();
        });
        
        // 阻止移动端的默认滚动和缩放
        if (this.isMobile) {
            // 阻止整个页面的触摸滚动，但允许开始界面的交互
            document.addEventListener('touchmove', (e) => {
                // 如果开始界面或死亡界面显示，允许触摸事件
                const gameOverlay = document.getElementById('gameOverlay');
                if (gameOverlay && window.getComputedStyle(gameOverlay).display !== 'none') {
                    return;
                }
                e.preventDefault();
            }, { passive: false });
            
            document.addEventListener('touchstart', (e) => {
                // 如果开始界面或死亡界面显示，允许触摸事件
                const gameOverlay = document.getElementById('gameOverlay');
                if (gameOverlay && window.getComputedStyle(gameOverlay).display !== 'none') {
                    return;
                }
                e.preventDefault();
            }, { passive: false });
            
            document.addEventListener('gesturestart', (e) => {
                e.preventDefault();
            });
            
            // 阻止页面缩放
            document.addEventListener('gesturechange', (e) => {
                e.preventDefault();
            });
            
            document.addEventListener('gestureend', (e) => {
                e.preventDefault();
            });
        }
    }
    
    setupTouchControls() {
        // 设置滑动控制（仅移动设备）
        if (this.isMobile) {
            const touchArea = document.getElementById('touchArea');
            if (touchArea) {
            touchArea.addEventListener('touchstart', (e) => {
                e.preventDefault();
                e.stopPropagation();
                const touch = e.touches[0];
                this.touchStartX = touch.clientX;
                this.touchStartY = touch.clientY;
            }, { passive: false });
            
            touchArea.addEventListener('touchmove', (e) => {
                e.preventDefault();
                e.stopPropagation();
            }, { passive: false });
            
            touchArea.addEventListener('touchend', (e) => {
                e.preventDefault();
                e.stopPropagation();
                if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
                
                const touch = e.changedTouches[0];
                const deltaX = touch.clientX - this.touchStartX;
                const deltaY = touch.clientY - this.touchStartY;
                
                // 最小滑动距离
                const minSwipeDistance = 30;
                
                if (Math.abs(deltaX) < minSwipeDistance && Math.abs(deltaY) < minSwipeDistance) {
                    return;
                }
                
                let direction = null;
                
                // 判断滑动方向
                if (Math.abs(deltaX) > Math.abs(deltaY)) {
                    // 水平滑动
                    direction = { x: deltaX > 0 ? this.GRID_SIZE : -this.GRID_SIZE, y: 0 };
                } else {
                    // 垂直滑动
                    direction = { x: 0, y: deltaY > 0 ? this.GRID_SIZE : -this.GRID_SIZE };
                }
                
                if (direction && 
                    (direction.x !== this.lastDirection.x || direction.y !== this.lastDirection.y)) {
                    this.ws.send(JSON.stringify({
                        type: 'move',
                        direction: direction
                    }));
                    this.lastDirection = direction;
                    
                    // 显示方向提示
                    this.showDirectionFeedback(direction);
                }
            }, { passive: false });
            }
        }
        
        // 设置虚拟方向键控制（所有设备）
        this.setupVirtualKeypad();
        
        // 设置全屏控制
        this.setupFullscreenControls();
    }
    
    setupVirtualKeypad() {
        const upBtn = document.getElementById('virtualUp');
        const downBtn = document.getElementById('virtualDown');
        const leftBtn = document.getElementById('virtualLeft');
        const rightBtn = document.getElementById('virtualRight');
        
        if (upBtn) {
            // 触摸事件
            upBtn.addEventListener('touchstart', (e) => {
                e.preventDefault();
                this.sendVirtualDirection({ x: 0, y: -this.GRID_SIZE });
                upBtn.classList.add('active');
            }, { passive: false });
            
            upBtn.addEventListener('touchend', (e) => {
                e.preventDefault();
                upBtn.classList.remove('active');
            }, { passive: false });
            
            // 鼠标事件
            upBtn.addEventListener('mousedown', (e) => {
                e.preventDefault();
                this.sendVirtualDirection({ x: 0, y: -this.GRID_SIZE });
                upBtn.classList.add('active');
            });
            
            upBtn.addEventListener('mouseup', (e) => {
                e.preventDefault();
                upBtn.classList.remove('active');
            });
            
            upBtn.addEventListener('mouseleave', (e) => {
                upBtn.classList.remove('active');
            });
        }
        
        if (downBtn) {
            // 触摸事件
            downBtn.addEventListener('touchstart', (e) => {
                e.preventDefault();
                this.sendVirtualDirection({ x: 0, y: this.GRID_SIZE });
                downBtn.classList.add('active');
            }, { passive: false });
            
            downBtn.addEventListener('touchend', (e) => {
                e.preventDefault();
                downBtn.classList.remove('active');
            }, { passive: false });
            
            // 鼠标事件
            downBtn.addEventListener('mousedown', (e) => {
                e.preventDefault();
                this.sendVirtualDirection({ x: 0, y: this.GRID_SIZE });
                downBtn.classList.add('active');
            });
            
            downBtn.addEventListener('mouseup', (e) => {
                e.preventDefault();
                downBtn.classList.remove('active');
            });
            
            downBtn.addEventListener('mouseleave', (e) => {
                downBtn.classList.remove('active');
            });
        }
        
        if (leftBtn) {
            // 触摸事件
            leftBtn.addEventListener('touchstart', (e) => {
                e.preventDefault();
                this.sendVirtualDirection({ x: -this.GRID_SIZE, y: 0 });
                leftBtn.classList.add('active');
            }, { passive: false });
            
            leftBtn.addEventListener('touchend', (e) => {
                e.preventDefault();
                leftBtn.classList.remove('active');
            }, { passive: false });
            
            // 鼠标事件
            leftBtn.addEventListener('mousedown', (e) => {
                e.preventDefault();
                this.sendVirtualDirection({ x: -this.GRID_SIZE, y: 0 });
                leftBtn.classList.add('active');
            });
            
            leftBtn.addEventListener('mouseup', (e) => {
                e.preventDefault();
                leftBtn.classList.remove('active');
            });
            
            leftBtn.addEventListener('mouseleave', (e) => {
                leftBtn.classList.remove('active');
            });
        }
        
        if (rightBtn) {
            // 触摸事件
            rightBtn.addEventListener('touchstart', (e) => {
                e.preventDefault();
                this.sendVirtualDirection({ x: this.GRID_SIZE, y: 0 });
                rightBtn.classList.add('active');
            }, { passive: false });
            
            rightBtn.addEventListener('touchend', (e) => {
                e.preventDefault();
                rightBtn.classList.remove('active');
            }, { passive: false });
            
            // 鼠标事件
            rightBtn.addEventListener('mousedown', (e) => {
                e.preventDefault();
                this.sendVirtualDirection({ x: this.GRID_SIZE, y: 0 });
                rightBtn.classList.add('active');
            });
            
            rightBtn.addEventListener('mouseup', (e) => {
                e.preventDefault();
                rightBtn.classList.remove('active');
            });
            
            rightBtn.addEventListener('mouseleave', (e) => {
                rightBtn.classList.remove('active');
            });
        }
    }
    
    sendVirtualDirection(direction) {
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
        
        if (direction.x !== this.lastDirection.x || direction.y !== this.lastDirection.y) {
            this.ws.send(JSON.stringify({
                type: 'move',
                direction: direction
            }));
            this.lastDirection = direction;
        }
    }
    
    showDirectionFeedback(direction) {
        const touchHint = document.querySelector('.touch-hint');
        if (!touchHint) return;
        
        let directionText = '';
        if (direction.x > 0) directionText = '→ 向右';
        else if (direction.x < 0) directionText = '← 向左';
        else if (direction.y > 0) directionText = '↓ 向下';
        else if (direction.y < 0) directionText = '↑ 向上';
        
        touchHint.textContent = directionText;
        touchHint.style.color = '#4CAF50';
        
        setTimeout(() => {
            touchHint.textContent = '滑动控制方向';
            touchHint.style.color = 'rgba(255, 255, 255, 0.7)';
        }, 1000);
    }
    
    adjustCanvasForMobile() {
        if (!this.isMobile) return;
        
        const canvas = this.canvas;
        
        // 移动端全屏显示 - 完全填充屏幕消除白边
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;
        
        // 直接设置为全屏尺寸，消除白边
        canvas.style.width = '100vw';
        canvas.style.height = '100vh';
        canvas.style.left = '0px';
        canvas.style.top = '0px';
        canvas.style.position = 'fixed';
        canvas.style.margin = '0';
        canvas.style.padding = '0';
        canvas.style.border = 'none';
        canvas.style.outline = 'none';
        
        // 确保canvas完全覆盖屏幕
        canvas.style.minWidth = '100vw';
        canvas.style.minHeight = '100vh';
        canvas.style.maxWidth = '100vw';
        canvas.style.maxHeight = '100vh';
        canvas.style.objectFit = 'cover';
        canvas.style.objectPosition = 'center';
    }
    
    setupOrientationHandling() {
        if (!this.isMobile) return;
        
        const orientationPrompt = document.getElementById('orientationPrompt');
        
        // 检查屏幕方向
        const checkOrientation = () => {
            const isPortrait = window.innerHeight > window.innerWidth;
            
            if (orientationPrompt) {
                if (isPortrait) {
                    orientationPrompt.style.display = 'flex';
                } else {
                    orientationPrompt.style.display = 'none';
                    // 横屏时重新调整画布尺寸
                    this.updateCanvasSize();
                    this.adjustCanvasForMobile();
                    this.adjustResponsiveLayout();
                }
            }
        };
        
        // 初始检查
        checkOrientation();
        
        // 监听屏幕方向变化
        window.addEventListener('orientationchange', () => {
            setTimeout(checkOrientation, 100); // 延迟检查，等待方向变化完成
        });
        
        window.addEventListener('resize', checkOrientation);
        
        // 尝试自动横屏（仅在支持的浏览器中）
        this.requestLandscapeOrientation();
    }
    
    requestLandscapeOrientation() {
        if (!this.isMobile) return;
        
        // 尝试使用Screen Orientation API
        if (screen && screen.orientation && screen.orientation.lock) {
            screen.orientation.lock('landscape').catch(err => {
                console.log('无法锁定横屏方向:', err);
            });
        }
        // 对于iOS Safari，尝试使用webkit前缀
        else if (screen && screen.lockOrientation) {
            screen.lockOrientation('landscape');
        }
        // 对于旧版本浏览器
        else if (screen && screen.webkitLockOrientation) {
            screen.webkitLockOrientation('landscape');
        }
        else if (screen && screen.mozLockOrientation) {
            screen.mozLockOrientation('landscape');
        }
    }
    
    adjustResponsiveLayout() {
        if (!this.isMobile) return;
        
        const isLandscape = window.innerWidth > window.innerHeight;
        const isSmallScreen = window.innerWidth <= 480;
        const gameInfo = document.querySelector('.mobile-game-info');
        const leaderboard = document.querySelector('.game-leaderboard');
        const virtualKeypad = document.querySelector('.virtual-keypad');
        
        if (isLandscape) {
            // 横屏模式下的响应式调整
            if (isSmallScreen) {
                // 小屏幕横屏：隐藏排行榜，只保留基本信息
                if (leaderboard) {
                    leaderboard.style.display = 'none';
                }
                if (gameInfo) {
                    gameInfo.style.fontSize = '9px';
                    gameInfo.style.padding = '3px 6px';
                }
                if (virtualKeypad) {
                    virtualKeypad.style.transform = 'scale(0.8)';
                }
            } else {
                // 中等屏幕横屏：显示所有元素但缩小
                if (leaderboard) {
                    leaderboard.style.display = 'block';
                }
                if (gameInfo) {
                    gameInfo.style.fontSize = '10px';
                    gameInfo.style.padding = '4px 8px';
                }
                if (virtualKeypad) {
                    virtualKeypad.style.transform = 'scale(0.9)';
                }
            }
        } else {
            // 竖屏模式：恢复正常显示
            if (leaderboard) {
                leaderboard.style.display = 'block';
            }
            if (gameInfo) {
                gameInfo.style.fontSize = '';
                gameInfo.style.padding = '';
            }
            if (virtualKeypad) {
                virtualKeypad.style.transform = '';
            }
        }
    }
    
    connectToServer(name) {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const wsUrl = `${protocol}//${window.location.host}`;
        
        this.ws = new WebSocket(wsUrl);
        
        this.ws.onopen = () => {
            console.log('连接到服务器');
            this.updateConnectionStatus(true);
            
            // 发送画布尺寸信息
            this.ws.send(JSON.stringify({
                type: 'updateCanvasSize',
                canvasWidth: this.CANVAS_WIDTH,
                canvasHeight: this.CANVAS_HEIGHT
            }));
            
            // 发送加入游戏请求
            this.ws.send(JSON.stringify({
                type: 'join',
                name: name,
                avatar: this.selectedAvatar
            }));
        };
        
        this.ws.onmessage = (event) => {
            const data = JSON.parse(event.data);
            this.handleServerMessage(data);
        };
        
        this.ws.onclose = () => {
            console.log('与服务器断开连接');
            this.updateConnectionStatus(false);
            setTimeout(() => {
                if (this.playerName) {
                    this.connectToServer(this.playerName);
                }
            }, 3000);
        };
        
        this.ws.onerror = (error) => {
            console.error('WebSocket错误:', error);
            this.updateConnectionStatus(false);
        };
    }
    
    handleServerMessage(data) {
        switch (data.type) {
            case 'joined':
                this.playerId = data.playerId;
                this.playerName = data.playerName;
                this.elements.playerName.textContent = this.playerName;
                
                // 更新世界尺寸为服务器发送的实际尺寸
                if (data.worldWidth && data.worldHeight) {
                    this.WORLD_WIDTH = data.worldWidth;
                    this.WORLD_HEIGHT = data.worldHeight;
                    console.log(`客户端世界尺寸已同步: ${this.WORLD_WIDTH}x${this.WORLD_HEIGHT}`);
                }
                
                this.hideStartScreen();
                
                // 自动进入全屏模式
                setTimeout(() => {
                    const gameArea = document.querySelector('.game-area');
                    if (gameArea) {
                        this.enterFullscreen(gameArea);
                    }
                }, 100);
                
                // 初始化摄像头位置到世界中心，等待玩家数据
                this.camera.x = (this.WORLD_WIDTH - this.CANVAS_WIDTH) / 2;
                this.camera.y = (this.WORLD_HEIGHT - this.CANVAS_HEIGHT) / 2;
                this.camera.targetX = this.camera.x;
                this.camera.targetY = this.camera.y;
                
                // 自动进入全屏模式
                setTimeout(() => {
                    const gameArea = document.querySelector('.game-area');
                    if (gameArea) {
                        this.toggleFullscreen(gameArea);
                    }
                }, 500); // 延迟500ms确保界面已经准备好
                break;
                
            case 'gameState':
                this.gameState = data;
                
                // 如果是第一次收到玩家数据，立即将摄像头跳转到玩家位置
                const currentPlayer = this.gameState.players.find(p => p.id === this.playerId);
                if (currentPlayer && currentPlayer.snake && currentPlayer.snake.length > 0) {
                    const head = currentPlayer.snake[0];
                    const targetX = head.x - this.CANVAS_WIDTH / 2;
                    const targetY = head.y - this.CANVAS_HEIGHT / 2;
                    
                    // 如果摄像头还在初始位置（世界中心），直接跳转到玩家位置
                    const worldCenterX = (this.WORLD_WIDTH - this.CANVAS_WIDTH) / 2;
                    const worldCenterY = (this.WORLD_HEIGHT - this.CANVAS_HEIGHT) / 2;
                    
                    if (Math.abs(this.camera.x - worldCenterX) < 10 && Math.abs(this.camera.y - worldCenterY) < 10) {
                        this.camera.x = Math.max(0, Math.min(this.WORLD_WIDTH - this.CANVAS_WIDTH, targetX));
                        this.camera.y = Math.max(0, Math.min(this.WORLD_HEIGHT - this.CANVAS_HEIGHT, targetY));
                        this.camera.targetX = this.camera.x;
                        this.camera.targetY = this.camera.y;
                    }
                }
                
                this.updateUI();
                this.render();
                break;
                
            case 'playerDied':
                this.showDeathScreen(data.score, data.length, data.cause);
                break;
            case 'death':
                this.showDeathScreen(data.score, data.length, data.cause);
                break;
                
            case 'respawned':
                this.hideDeathScreen();
                break;
                
            case 'worldMessage':
                this.addWorldMessage(data.message, data.timestamp);
                break;
                
            case 'error':
                alert(data.message);
                break;
        }
    }
    
    handleKeyPress(key) {
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
        
        let direction = null;
        
        switch (key) {
            case 'ArrowUp':
            case 'w':
            case 'W':
                direction = { x: 0, y: -this.GRID_SIZE };
                break;
            case 'ArrowDown':
            case 's':
            case 'S':
                direction = { x: 0, y: this.GRID_SIZE };
                break;
            case 'ArrowLeft':
            case 'a':
            case 'A':
                direction = { x: -this.GRID_SIZE, y: 0 };
                break;
            case 'ArrowRight':
            case 'd':
            case 'D':
                direction = { x: this.GRID_SIZE, y: 0 };
                break;
        }
        
        if (direction && 
            (direction.x !== this.lastDirection.x || direction.y !== this.lastDirection.y)) {
            this.ws.send(JSON.stringify({
                type: 'move',
                direction: direction
            }));
            this.lastDirection = direction;
        }
    }
    
    updateCamera() {
        // 找到当前玩家
        const currentPlayer = this.gameState.players.find(p => p.id === this.playerId);
        if (currentPlayer && currentPlayer.snake && currentPlayer.snake.length > 0) {
            // 设置摄像头目标为玩家头部位置
            const head = currentPlayer.snake[0];
            this.camera.targetX = head.x - this.CANVAS_WIDTH / 2;
            this.camera.targetY = head.y - this.CANVAS_HEIGHT / 2;
            
            // 限制摄像头在世界边界内
            this.camera.targetX = Math.max(0, Math.min(this.WORLD_WIDTH - this.CANVAS_WIDTH, this.camera.targetX));
            this.camera.targetY = Math.max(0, Math.min(this.WORLD_HEIGHT - this.CANVAS_HEIGHT, this.camera.targetY));
            
            // 计算距离，如果玩家移动太快或距离太远，直接跳转而不是平滑移动
            const distanceX = Math.abs(this.camera.targetX - this.camera.x);
            const distanceY = Math.abs(this.camera.targetY - this.camera.y);
            const maxDistance = Math.min(this.CANVAS_WIDTH, this.CANVAS_HEIGHT) * 0.3;
            
            if (distanceX > maxDistance || distanceY > maxDistance) {
                // 距离太远，直接跳转
                this.camera.x = this.camera.targetX;
                this.camera.y = this.camera.targetY;
            } else {
                // 平滑移动摄像头
                this.camera.x += (this.camera.targetX - this.camera.x) * this.camera.smoothing;
                this.camera.y += (this.camera.targetY - this.camera.y) * this.camera.smoothing;
            }
        }
    }
    
    worldToScreen(worldX, worldY) {
        return {
            x: worldX - this.camera.x,
            y: worldY - this.camera.y
        };
    }
    
    isInViewport(worldX, worldY, size = this.GRID_SIZE) {
        const screen = this.worldToScreen(worldX, worldY);
        return screen.x + size >= 0 && screen.x <= this.CANVAS_WIDTH && 
               screen.y + size >= 0 && screen.y <= this.CANVAS_HEIGHT;
    }
    
    render() {
        // 更新摄像头
        this.updateCamera();
        
        // 绘制背景
        if (this.backgroundImageLoaded) {
            // 单张大地图缩放显示
            this.ctx.drawImage(
                this.backgroundImage, 
                0, 0, 
                this.CANVAS_WIDTH, 
                this.CANVAS_HEIGHT
            );
        } else {
            // 背景图片未加载时使用默认颜色
            this.ctx.fillStyle = '#2c3e50';
            this.ctx.fillRect(0, 0, this.CANVAS_WIDTH, this.CANVAS_HEIGHT);
        }
        
        // 保存当前变换状态
        this.ctx.save();
        
        // 应用摄像头变换
        this.ctx.translate(-this.camera.x, -this.camera.y);
        
        // 绘制世界边界
        this.drawWorldBounds();
        
        // 绘制网格
        this.drawGrid();
        
        // 绘制食物
        this.drawFoods();
        
        // 绘制道具
        this.drawPowerUps();
        
        // 绘制所有蛇
        this.drawSnakes();
        
        // 绘制妖怪
        this.drawMonsters();
        
        // 绘制特效
        this.drawEffects();
        
        // 恢复变换状态
        this.ctx.restore();
        
        // 绘制缩略地图
        this.drawMinimap();
    }
    
    drawMinimap() {
        const minimapSize = 200;
        const minimapX = 20;
        const minimapY = this.CANVAS_HEIGHT - minimapSize - 20;
        
        // 绘制缩略地图背景
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
        this.ctx.fillRect(minimapX, minimapY, minimapSize, minimapSize);
        
        // 绘制缩略地图边框
        this.ctx.strokeStyle = '#ffffff';
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(minimapX, minimapY, minimapSize, minimapSize);
        
        // 计算缩放比例
        const scaleX = minimapSize / this.WORLD_WIDTH;
        const scaleY = minimapSize / this.WORLD_HEIGHT;
        
        // 绘制世界边界
        this.ctx.strokeStyle = '#e74c3c';
        this.ctx.lineWidth = 1;
        this.ctx.strokeRect(minimapX, minimapY, minimapSize, minimapSize);
        
        // 绘制所有玩家在缩略地图上的位置
        this.gameState.players.forEach(player => {
            if (!player.alive || !player.body || player.body.length === 0) return;
            
            const head = player.body[0];
            const mapX = minimapX + head.x * scaleX;
            const mapY = minimapY + head.y * scaleY;
            
            // 绘制玩家点
            this.ctx.fillStyle = player.color || '#ffffff';
            this.ctx.beginPath();
            this.ctx.arc(mapX, mapY, 3, 0, 2 * Math.PI);
            this.ctx.fill();
            
            // 高亮当前玩家
            if (player.id === this.playerId) {
                this.ctx.strokeStyle = '#ffff00';
                this.ctx.lineWidth = 2;
                this.ctx.beginPath();
                this.ctx.arc(mapX, mapY, 5, 0, 2 * Math.PI);
                this.ctx.stroke();
            }
        });
        
        // 绘制当前视角范围
        const viewX = minimapX + this.camera.x * scaleX;
        const viewY = minimapY + this.camera.y * scaleY;
        const viewWidth = this.CANVAS_WIDTH * scaleX;
        const viewHeight = this.CANVAS_HEIGHT * scaleY;
        
        this.ctx.strokeStyle = '#00ff00';
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(viewX, viewY, viewWidth, viewHeight);
        
        // 添加缩略地图标题
        this.ctx.fillStyle = '#ffffff';
        this.ctx.font = '12px Arial';
        this.ctx.textAlign = 'left';
        this.ctx.fillText('地图', minimapX, minimapY - 5);
    }
    
    drawWorldBounds() {
        // 绘制世界边界
        this.ctx.strokeStyle = '#e74c3c';
        this.ctx.lineWidth = 4;
        this.ctx.strokeRect(0, 0, this.WORLD_WIDTH, this.WORLD_HEIGHT);
    }
    
    drawGrid() {
        this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
        this.ctx.lineWidth = 1;
        
        // 计算可见区域的网格范围
        const startX = Math.floor(this.camera.x / this.GRID_SIZE) * this.GRID_SIZE;
        const endX = Math.min(this.WORLD_WIDTH, this.camera.x + this.CANVAS_WIDTH + this.GRID_SIZE);
        const startY = Math.floor(this.camera.y / this.GRID_SIZE) * this.GRID_SIZE;
        const endY = Math.min(this.WORLD_HEIGHT, this.camera.y + this.CANVAS_HEIGHT + this.GRID_SIZE);
        
        // 绘制垂直线
        for (let x = startX; x <= endX; x += this.GRID_SIZE) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, Math.max(0, this.camera.y));
            this.ctx.lineTo(x, Math.min(this.WORLD_HEIGHT, this.camera.y + this.CANVAS_HEIGHT));
            this.ctx.stroke();
        }
        
        // 绘制水平线
        for (let y = startY; y <= endY; y += this.GRID_SIZE) {
            this.ctx.beginPath();
            this.ctx.moveTo(Math.max(0, this.camera.x), y);
            this.ctx.lineTo(Math.min(this.WORLD_WIDTH, this.camera.x + this.CANVAS_WIDTH), y);
            this.ctx.stroke();
        }
    }
    
    drawFoods() {
        this.gameState.foods.forEach(food => {
            // 只绘制在视口内的食物
            if (!this.isInViewport(food.x, food.y)) return;
            
            const gradient = this.ctx.createRadialGradient(
                food.x + this.GRID_SIZE/2, food.y + this.GRID_SIZE/2, 0,
                food.x + this.GRID_SIZE/2, food.y + this.GRID_SIZE/2, this.GRID_SIZE/2
            );
            
            // 根据食物价值设置颜色
            switch (food.value) {
                case 1:
                    gradient.addColorStop(0, '#FF6B6B');
                    gradient.addColorStop(1, '#FF5252');
                    break;
                case 2:
                    gradient.addColorStop(0, '#4ECDC4');
                    gradient.addColorStop(1, '#26A69A');
                    break;
                case 3:
                    gradient.addColorStop(0, '#FFD93D');
                    gradient.addColorStop(1, '#FFC107');
                    break;
            }
            
            this.ctx.fillStyle = gradient;
            this.ctx.beginPath();
            this.ctx.arc(
                food.x + this.GRID_SIZE/2,
                food.y + this.GRID_SIZE/2,
                this.GRID_SIZE/2 - 2,
                0, 2 * Math.PI
            );
            this.ctx.fill();
            
            // 绘制食物价值
            this.ctx.fillStyle = 'white';
            this.ctx.font = 'bold 12px Arial';
            this.ctx.textAlign = 'center';
            this.ctx.fillText(
                food.value,
                food.x + this.GRID_SIZE/2,
                food.y + this.GRID_SIZE/2 + 4
            );
        });
    }
    
    drawPowerUps() {
        this.gameState.powerUps.forEach(powerUp => {
            // 只绘制在视口内的道具
            if (!this.isInViewport(powerUp.x, powerUp.y)) return;
            
            // 根据道具类型设置颜色
            let backgroundColor, borderColor;
            switch (powerUp.type) {
                case 'mine':
                    backgroundColor = '#ff4444';
                    borderColor = '#cc0000';
                    break;
                case 'double':
                    backgroundColor = '#44ff44';
                    borderColor = '#00cc00';
                    break;
                default:
                    backgroundColor = powerUp.color || '#4444ff';
                    borderColor = '#ffffff';
            }
            
            // 绘制道具背景
            this.ctx.fillStyle = backgroundColor;
            this.ctx.fillRect(powerUp.x + 2, powerUp.y + 2, this.GRID_SIZE - 4, this.GRID_SIZE - 4);
            
            // 绘制道具图标
            this.ctx.fillStyle = 'white';
            this.ctx.font = 'bold 14px Arial';
            this.ctx.textAlign = 'center';
            
            let icon = '?';
            switch (powerUp.type) {
                case 'mine': icon = '💣'; break;
                case 'double': icon = '×2'; break;
                case 'speed': icon = '⚡'; break;
                case 'invincible': icon = '🛡'; break;
                case 'shrink': icon = '↓'; break;
                case 'grow': icon = '↑'; break;
                case 'invisible': icon = '👻'; break;
                case 'shield': icon = '🔰'; break;
                case 'magnet': icon = '🧲'; break;
            }
            
            this.ctx.fillText(
                icon,
                powerUp.x + this.GRID_SIZE/2,
                powerUp.y + this.GRID_SIZE/2 + 5
            );
            
            // 绘制边框
            this.ctx.strokeStyle = borderColor;
            this.ctx.lineWidth = 2;
            this.ctx.strokeRect(powerUp.x, powerUp.y, this.GRID_SIZE, this.GRID_SIZE);
            
            // 绘制闪烁效果
            const time = Date.now();
            const alpha = 0.3 + 0.3 * Math.sin(time * 0.01);
            this.ctx.fillStyle = `rgba(255, 255, 255, ${alpha})`;
            this.ctx.fillRect(powerUp.x, powerUp.y, this.GRID_SIZE, this.GRID_SIZE);
        });
    }
    
    drawSnakes() {
        this.gameState.players.forEach(player => {
            if (!player.alive || player.snake.length === 0) return;
            
            // 绘制蛇身
            player.snake.forEach((segment, index) => {
                // 只绘制在视口内的蛇身片段
                if (!this.isInViewport(segment.x, segment.y)) return;
                
                const isHead = index === 0;
                let alpha = 1.0;
                
                // 根据道具效果调整透明度
                if (player.effects.includes('invincible')) alpha = 0.7;
                if (player.effects.includes('invisible')) alpha = 0.3;
                if (player.effects.includes('shield')) {
                    // 护盾效果：闪烁
                    const time = Date.now();
                    alpha = 0.8 + 0.2 * Math.sin(time * 0.01);
                }
                
                if (isHead) {
                    // 绘制蛇头
                    const gradient = this.ctx.createRadialGradient(
                        segment.x + this.GRID_SIZE/2, segment.y + this.GRID_SIZE/2, 0,
                        segment.x + this.GRID_SIZE/2, segment.y + this.GRID_SIZE/2, this.GRID_SIZE/2
                    );
                    gradient.addColorStop(0, this.lightenColor(player.color, 20));
                    gradient.addColorStop(1, player.color);
                    
                    this.ctx.globalAlpha = alpha;
                    this.ctx.fillStyle = gradient;
                    this.ctx.fillRect(segment.x + 1, segment.y + 1, this.GRID_SIZE - 2, this.GRID_SIZE - 2);
                    
                    // 绘制头像图标
                    const avatarIcons = ['🐗', '🦫', '🐸', '🦍'];
                const avatarIcon = avatarIcons[player.avatar] || '🐗';
                    
                    this.ctx.font = `${this.GRID_SIZE - 4}px Arial`;
                    this.ctx.textAlign = 'center';
                    this.ctx.textBaseline = 'middle';
                    this.ctx.fillStyle = 'white';
                    this.ctx.fillText(
                        avatarIcon, 
                        segment.x + this.GRID_SIZE/2, 
                        segment.y + this.GRID_SIZE/2
                    );
                } else {
                    // 绘制蛇身
                    const bodyAlpha = alpha * (0.8 - index * 0.02);
                    this.ctx.globalAlpha = Math.max(bodyAlpha, 0.3);
                    this.ctx.fillStyle = player.color;
                    this.ctx.fillRect(segment.x + 2, segment.y + 2, this.GRID_SIZE - 4, this.GRID_SIZE - 4);
                }
            });
            
            this.ctx.globalAlpha = 1.0;
            
            // 绘制玩家名称和分数
            const head = player.snake[0];
            this.ctx.fillStyle = 'white';
            this.ctx.font = 'bold 12px Arial';
            this.ctx.textAlign = 'center';
            this.ctx.strokeStyle = 'black';
            this.ctx.lineWidth = 2;
            
            const text = `${player.name} (${player.score})`;
            this.ctx.strokeText(text, head.x + this.GRID_SIZE/2, head.y - 5);
            this.ctx.fillText(text, head.x + this.GRID_SIZE/2, head.y - 5);
            
            // 绘制当前玩家的特殊标记
            if (player.id === this.playerId) {
                this.ctx.strokeStyle = '#FFD700';
                this.ctx.lineWidth = 3;
                this.ctx.strokeRect(head.x - 2, head.y - 2, this.GRID_SIZE + 4, this.GRID_SIZE + 4);
            }
        });
    }
    
    drawMonsters() {
        if (!this.gameState.monsters) return;
        
        this.gameState.monsters.forEach(monster => {
            if (!monster.alive || monster.snake.length === 0) return;
            
            // 绘制妖怪蛇身
            monster.snake.forEach((segment, index) => {
                // 只绘制在视口内的蛇身片段
                if (!this.isInViewport(segment.x, segment.y)) return;
                
                const isHead = index === 0;
                const segmentSize = this.GRID_SIZE * monster.size;
                const offset = (segmentSize - this.GRID_SIZE) / 2;
                
                if (isHead) {
                    // 绘制妖怪头部光环效果
                    const time = Date.now() * 0.005;
                    const glowRadius = segmentSize/2 + Math.sin(time) * 3;
                    const glowGradient = this.ctx.createRadialGradient(
                        segment.x + segmentSize/2 - offset, segment.y + segmentSize/2 - offset, 0,
                        segment.x + segmentSize/2 - offset, segment.y + segmentSize/2 - offset, glowRadius
                    );
                    glowGradient.addColorStop(0, monster.color + '80');
                    glowGradient.addColorStop(0.7, monster.color + '40');
                    glowGradient.addColorStop(1, monster.color + '00');
                    
                    this.ctx.fillStyle = glowGradient;
                    this.ctx.fillRect(
                        segment.x - offset - 5, 
                        segment.y - offset - 5, 
                        segmentSize + 10, 
                        segmentSize + 10
                    );
                    
                    // 绘制妖怪头部主体
                    const gradient = this.ctx.createRadialGradient(
                        segment.x + segmentSize/2 - offset, segment.y + segmentSize/2 - offset, 0,
                        segment.x + segmentSize/2 - offset, segment.y + segmentSize/2 - offset, segmentSize/2
                    );
                    gradient.addColorStop(0, this.lightenColor(monster.color, 40));
                    gradient.addColorStop(0.6, monster.color);
                    gradient.addColorStop(1, this.lightenColor(monster.color, -20));
                    
                    this.ctx.fillStyle = gradient;
                    this.ctx.fillRect(
                        segment.x - offset + 1, 
                        segment.y - offset + 1, 
                        segmentSize - 2, 
                        segmentSize - 2
                    );
                    
                    // 绘制妖怪图标
                    const monsterIcons = {
                        'dawang': '👹',
                        'laoshu': '🐭', 
                        'huangmei': '👺'
                    };
                    const monsterIcon = monsterIcons[monster.type] || '👹';
                    
                    this.ctx.font = `${Math.floor(segmentSize * 0.8)}px Arial`;
                    this.ctx.textAlign = 'center';
                    this.ctx.textBaseline = 'middle';
                    
                    // 图标阴影效果
                    this.ctx.fillStyle = 'rgba(0,0,0,0.8)';
                    this.ctx.fillText(
                        monsterIcon, 
                        segment.x + this.GRID_SIZE/2 + 2, 
                        segment.y + this.GRID_SIZE/2 + 2
                    );
                    
                    // 图标主体
                    this.ctx.fillStyle = monster.textColor;
                    this.ctx.fillText(
                        monsterIcon, 
                        segment.x + this.GRID_SIZE/2, 
                        segment.y + this.GRID_SIZE/2
                    );
                    
                    // 绘制脉冲边框
                    const pulseWidth = 2 + Math.sin(time * 2) * 1;
                    this.ctx.strokeStyle = monster.textColor;
                    this.ctx.lineWidth = pulseWidth;
                    this.ctx.strokeRect(
                        segment.x - offset, 
                        segment.y - offset, 
                        segmentSize, 
                        segmentSize
                    );
                    
                    // 绘制内部边框
                    this.ctx.strokeStyle = this.lightenColor(monster.textColor, 50);
                    this.ctx.lineWidth = 1;
                    this.ctx.strokeRect(
                        segment.x - offset + 3, 
                        segment.y - offset + 3, 
                        segmentSize - 6, 
                        segmentSize - 6
                    );
                } else {
                    // 绘制妖怪身体 - 增强视觉效果
                    const bodyAlpha = 0.9 - index * 0.02;
                    this.ctx.globalAlpha = Math.max(bodyAlpha, 0.5);
                    
                    // 身体渐变效果
                    const bodyGradient = this.ctx.createLinearGradient(
                        segment.x - offset, segment.y - offset,
                        segment.x - offset + segmentSize, segment.y - offset + segmentSize
                    );
                    bodyGradient.addColorStop(0, this.lightenColor(monster.color, 20));
                    bodyGradient.addColorStop(1, this.lightenColor(monster.color, -10));
                    
                    this.ctx.fillStyle = bodyGradient;
                    this.ctx.fillRect(
                        segment.x - offset + 2, 
                        segment.y - offset + 2, 
                        segmentSize - 4, 
                        segmentSize - 4
                    );
                    
                    // 身体边框
                    this.ctx.globalAlpha = bodyAlpha * 0.8;
                    this.ctx.strokeStyle = this.lightenColor(monster.color, -30);
                    this.ctx.lineWidth = 1;
                    this.ctx.strokeRect(
                        segment.x - offset + 2, 
                        segment.y - offset + 2, 
                        segmentSize - 4, 
                        segmentSize - 4
                    );
                }
            });
            
            this.ctx.globalAlpha = 1.0;
            
            // 绘制妖怪名称和等级标识 - 增强效果
            const head = monster.snake[0];
            const textY = head.y - 12;
            const time = Date.now() * 0.003;
            
            // 名称文字
            this.ctx.font = 'bold 15px Arial';
            this.ctx.textAlign = 'center';
            
            const text = `${monster.name} [Lv.${monster.level}] (${monster.snake.length})`;
            
            // 文字外发光效果
            this.ctx.shadowColor = monster.color;
            this.ctx.shadowBlur = 8;
            this.ctx.fillStyle = 'black';
            this.ctx.fillText(text, head.x + this.GRID_SIZE/2, textY);
            
            // 重置阴影
            this.ctx.shadowBlur = 0;
            
            // 文字描边
            this.ctx.strokeStyle = 'black';
            this.ctx.lineWidth = 4;
            this.ctx.strokeText(text, head.x + this.GRID_SIZE/2, textY);
            
            // 文字主体
            this.ctx.fillStyle = monster.textColor;
            this.ctx.fillText(text, head.x + this.GRID_SIZE/2, textY);
            
            // 动态警告标识
            const warningScale = 1 + Math.sin(time * 4) * 0.2;
            this.ctx.save();
            this.ctx.translate(head.x + this.GRID_SIZE/2, textY - 20);
            this.ctx.scale(warningScale, warningScale);
            
            this.ctx.fillStyle = '#FF0000';
            this.ctx.font = 'bold 18px Arial';
            this.ctx.textAlign = 'center';
            this.ctx.fillText('⚠️ 危险 ⚠️', 0, 0);
            
            this.ctx.restore();
            
            // 绘制威胁等级指示器
            const threatLevel = monster.level;
            for (let i = 0; i < threatLevel; i++) {
                this.ctx.fillStyle = i < threatLevel ? '#FF4444' : '#444444';
                this.ctx.fillRect(
                    head.x + this.GRID_SIZE/2 - 30 + i * 8, 
                    textY + 15, 
                    6, 
                    3
                );
            }
        });
    }
    
    drawEffects() {
        const currentPlayer = this.gameState.players.find(p => p.id === this.playerId);
        if (!currentPlayer || !currentPlayer.alive) return;
        
        // 绘制磁铁范围效果
        if (currentPlayer.effects.includes('magnet')) {
            const head = currentPlayer.snake[0];
            const magnetRange = this.GRID_SIZE * 3;
            
            this.ctx.strokeStyle = '#FF1493';
            this.ctx.lineWidth = 2;
            this.ctx.globalAlpha = 0.3;
            this.ctx.strokeRect(
                head.x - magnetRange, 
                head.y - magnetRange, 
                magnetRange * 2 + this.GRID_SIZE, 
                magnetRange * 2 + this.GRID_SIZE
            );
            this.ctx.globalAlpha = 1.0;
        }
        
        // 绘制道具效果提示
        let effectY = 10;
        currentPlayer.effects.forEach(effect => {
            let text = '';
            let color = 'white';
            
            switch (effect) {
                case 'speed':
                    text = '⚡ 加速中';
                    color = '#FFD700';
                    break;
                case 'invincible':
                    text = '🛡 无敌中';
                    color = '#FF69B4';
                    break;
                case 'double':
                    text = '×2 双倍分数';
                    color = '#00CED1';
                    break;
                case 'invisible':
                    text = '👻 隐身中';
                    color = '#9370DB';
                    break;
                case 'shield':
                    text = '🔰 护盾中';
                    color = '#4169E1';
                    break;
                case 'magnet':
                    text = '🧲 磁铁中';
                    color = '#FF1493';
                    break;
            }
            
            if (text) {
                this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
                this.ctx.fillRect(10, effectY, 120, 25);
                
                this.ctx.fillStyle = color;
                this.ctx.font = 'bold 14px Arial';
                this.ctx.textAlign = 'left';
                this.ctx.fillText(text, 15, effectY + 18);
                
                effectY += 30;
            }
        });
    }
    
    updateUI() {
        const currentPlayer = this.gameState.players.find(p => p.id === this.playerId);
        
        if (currentPlayer) {
            // 更新桌面端玩家信息
            if (this.elements.playerScore) {
                this.elements.playerScore.textContent = currentPlayer.score;
                this.elements.playerLength.textContent = currentPlayer.snake.length;
            }
            
            // 更新移动端玩家信息
            if (this.isMobile) {
                const mobilePlayerName = document.getElementById('mobilePlayerName');
                const mobilePlayerScore = document.getElementById('mobilePlayerScore');
                const mobilePlayerLength = document.getElementById('mobilePlayerLength');
                
                if (mobilePlayerName) mobilePlayerName.textContent = currentPlayer.name;
                if (mobilePlayerScore) mobilePlayerScore.textContent = currentPlayer.score;
                if (mobilePlayerLength) mobilePlayerLength.textContent = currentPlayer.snake.length;
            }
        }
        
        // 更新统计信息
        if (this.elements.onlineCount) {
            this.elements.onlineCount.textContent = this.gameState.players.filter(p => p.alive).length;
            this.elements.foodCount.textContent = this.gameState.foods.length;
            this.elements.powerUpCount.textContent = this.gameState.powerUps.length;
        }
        
        // 更新排行榜
        this.updateLeaderboard();
    }
    
    addWorldMessage(message, timestamp) {
        // 显示顶部消息通知
        this.showTopMessage(message);
    }
    
    showTopMessage(message) {
        if (!this.elements.topMessageNotification || !this.elements.topMessageContent) return;
        
        // 设置消息内容
        this.elements.topMessageContent.textContent = message;
        
        // 显示消息
        this.elements.topMessageNotification.style.display = 'block';
        this.elements.topMessageNotification.style.opacity = '1';
        
        // 清除之前的定时器
        if (this.topMessageTimer) {
            clearTimeout(this.topMessageTimer);
        }
        
        // 5秒后隐藏消息
        this.topMessageTimer = setTimeout(() => {
            this.hideTopMessage();
        }, 5000);
    }
    
    hideTopMessage() {
        if (!this.elements.topMessageNotification) return;
        
        // 淡出效果
        this.elements.topMessageNotification.style.opacity = '0';
        
        // 动画结束后隐藏
        setTimeout(() => {
            this.elements.topMessageNotification.style.display = 'none';
        }, 300);
    }
    
    updateLeaderboard() {
        const leaderboard = this.gameState.leaderboard || [];
        
        // 更新主排行榜
        if (leaderboard.length === 0) {
            this.elements.leaderboardList.innerHTML = '<div class="loading">等待玩家加入...</div>';
        } else {
            this.elements.leaderboardList.innerHTML = leaderboard.map(player => {
                const isCurrentPlayer = player.id === this.playerId;
                return `
                    <div class="leaderboard-item ${isCurrentPlayer ? 'current-player' : ''}">
                        <span class="player-rank">#${player.rank}</span>
                        <span class="player-name">${player.name}</span>
                        <span class="player-score">${player.score}</span>
                    </div>
                `;
            }).join('');
        }
        
        // 更新全屏排行榜
        const fullscreenLeaderboardList = document.getElementById('fullscreenLeaderboardList');
        if (fullscreenLeaderboardList) {
            if (leaderboard.length === 0) {
                fullscreenLeaderboardList.innerHTML = '<div class="loading">等待玩家加入...</div>';
            } else {
                fullscreenLeaderboardList.innerHTML = leaderboard.map(player => {
                    const isCurrentPlayer = player.id === this.playerId;
                    return `
                        <div class="leaderboard-item ${isCurrentPlayer ? 'current-player' : ''}">
                            <span class="player-rank">#${player.rank}</span>
                            <span class="player-name">${player.name}</span>
                            <span class="player-score">${player.score}</span>
                        </div>
                    `;
                }).join('');
            }
        }
    }
    
    updateConnectionStatus(connected) {
        // 更新桌面端连接状态
        const status = this.elements.connectionStatus;
        if (status) {
            if (connected) {
                status.textContent = '已连接';
                status.className = 'connected';
            } else {
                status.textContent = '连接中...';
                status.className = 'disconnected';
            }
        }
        
        // 更新移动端连接状态
        if (this.isMobile) {
            const mobileStatus = document.getElementById('mobileConnectionStatus');
            if (mobileStatus) {
                if (connected) {
                    mobileStatus.textContent = '已连接';
                    mobileStatus.className = 'connected';
                } else {
                    mobileStatus.textContent = '连接中...';
                    mobileStatus.className = 'disconnected';
                }
            }
        }
    }
    
    showPlayerSetup() {
        if (this.elements.playerSetupScreen) {
            this.elements.playerSetupScreen.style.display = 'flex';
        }
        if (this.elements.gameContainer) {
            this.elements.gameContainer.style.display = 'none';
        }
    }
    
    hidePlayerSetup() {
        if (this.elements.playerSetupScreen) {
            this.elements.playerSetupScreen.style.display = 'none';
        }
    }
    
    showGameInterface() {
        if (this.elements.gameContainer) {
            this.elements.gameContainer.style.display = 'block';
            // 添加游戏进行中的样式类
            this.elements.gameContainer.classList.add('playing');
        }
        
        // 激活游戏画布交互（游戏开始后）
        const gameCanvas = document.getElementById('gameCanvas');
        if (gameCanvas) {
            gameCanvas.classList.add('game-active');
        }
        
        // 设置游戏开始时间
        this.gameStartTime = Date.now();
    }
    
    hideGameInterface() {
        if (this.elements.gameContainer) {
            this.elements.gameContainer.style.display = 'none';
            // 移除游戏进行中的样式类
            this.elements.gameContainer.classList.remove('playing');
        }
        
        // 停用游戏画布交互
        const gameCanvas = document.getElementById('gameCanvas');
        if (gameCanvas) {
            gameCanvas.classList.remove('game-active');
        }
    }
    
    backToSetup() {
        // 断开连接
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.close();
        }
        
        // 隐藏游戏界面和死亡界面
        this.hideGameInterface();
        this.hideDeathScreen();
        
        // 显示玩家设置页面
        this.showPlayerSetup();
        
        console.log('返回设置页面');
    }
    
    showDeathScreen(score, length, cause) {
        if (this.elements.finalScore) {
            this.elements.finalScore.textContent = score;
        }
        if (this.elements.finalLength) {
            this.elements.finalLength.textContent = length;
        }
        
        // 根据死亡原因显示不同的消息
        const deathMessage = document.getElementById('deathMessage');
        if (deathMessage) {
            switch (cause) {
                case 'mine':
                    deathMessage.textContent = '💣 踩到地雷了！小心危险道具！';
                    break;
                case 'collision':
                    deathMessage.textContent = '💥 撞到了其他玩家！';
                    break;
                case 'wall':
                    deathMessage.textContent = '🧱 撞墙了！注意边界！';
                    break;
                case 'self':
                    deathMessage.textContent = '🐍 咬到自己了！';
                    break;
                default:
                    deathMessage.textContent = '游戏结束！';
            }
        }
        
        // 禁用游戏画布交互（游戏结束时）
        const gameCanvas = document.getElementById('gameCanvas');
        if (gameCanvas) {
            gameCanvas.classList.remove('game-active');
        }
        
        if (this.elements.deathScreen) {
            this.elements.deathScreen.style.display = 'block';
        }
        if (this.elements.gameOverlay) {
            this.elements.gameOverlay.style.display = 'flex';
        }
    }
    
    hideDeathScreen() {
        if (this.elements.deathScreen) {
            this.elements.deathScreen.style.display = 'none';
        }
        if (this.elements.gameOverlay) {
            this.elements.gameOverlay.style.display = 'none';
        }
    }
    
    respawn() {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify({ type: 'respawn' }));
            
            // 隐藏死亡界面
            this.hideDeathScreen();
            
            // 重新激活游戏画布
            const gameCanvas = document.getElementById('gameCanvas');
            if (gameCanvas) {
                gameCanvas.classList.add('game-active');
            }
            
            console.log('玩家重生');
        }
    }
    
    lightenColor(color, percent) {
        const num = parseInt(color.replace("#", ""), 16);
        const amt = Math.round(2.55 * percent);
        const R = (num >> 16) + amt;
        const G = (num >> 8 & 0x00FF) + amt;
        const B = (num & 0x0000FF) + amt;
        return "#" + (0x1000000 + (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 +
            (G < 255 ? G < 1 ? 0 : G : 255) * 0x100 +
            (B < 255 ? B < 1 ? 0 : B : 255))
            .toString(16).slice(1);
    }
    
    generateRandomName() {
        // 浪浪山相关的名字库
        const langlangshanNames = [
            // 浪浪山地名系列
            '浪浪山大王', '浪浪峰守护者', '浪浪谷探险家', '浪浪溪渔夫', '浪浪洞穴主', '浪浪石守卫', '浪浪林猎手', '浪浪湖船夫',
            '浪浪崖攀登者', '浪浪径行者', '浪浪坡牧羊人', '浪浪台观星者', '浪浪桥守桥人', '浪浪亭茶客', '浪浪寺僧人', '浪浪塔守塔人',
            
            // 山中生物系列
            '山中野猪王', '林间黄鼠狼', '溪边青蛙仙', '峰顶大猩猩', '云雾中的猴', '石缝里的蛇', '树洞中的熊', '草丛中的兔',
            '山泉边的鹿', '岩石上的鹰', '竹林里的熊猫', '花丛中的蝶', '月夜中的狼', '晨雾中的鹤', '夕阳下的虎', '星空下的猫头鹰',
            
            // 浪浪山传说系列
            '浪浪山传说', '古老的守护神', '神秘的山灵', '传说中的勇士', '古代的法师', '失落的王子', '隐居的仙人', '神话中的英雄',
            '远古的巫师', '传奇的猎人', '神秘的行者', '古老的智者', '传说的战士', '神话的守护', '远古的精灵', '传奇的探险者',
            
            // 浪浪山职业系列
            '浪浪山药师', '浪浪山铁匠', '浪浪山木匠', '浪浪山石匠', '浪浪山猎人', '浪浪山渔夫', '浪浪山农夫', '浪浪山商人',
            '浪浪山学者', '浪浪山画师', '浪浪山乐师', '浪浪山厨师', '浪浪山织工', '浪浪山陶工', '浪浪山园丁', '浪浪山牧人',
            
            // 浪浪山特色系列
            '踏浪而行', '听山而歌', '观云而思', '望月而叹', '追风而跑', '逐水而游', '寻花而舞', '听鸟而笑',
            '看星而梦', '闻香而醉', '品茶而悟', '弹琴而乐', '写字而静', '画画而美', '唱歌而欢', '跳舞而喜',
            
            // 浪浪山方位系列
            '东山日出', '西山日落', '南山竹海', '北山雪景', '山顶云海', '山腰花田', '山脚村庄', '山中古寺',
            '山前小溪', '山后密林', '山左石径', '山右花路', '山上仙境', '山下人间', '山内桃源', '山外红尘',
            
            // 浪浪山季节系列
            '春山花开', '夏山绿荫', '秋山红叶', '冬山雪白', '春雨润山', '夏风凉山', '秋霜染山', '冬雪覆山',
            '春鸟归山', '夏蝉鸣山', '秋雁过山', '冬梅傲山', '春笋破土', '夏荷盛开', '秋菊飘香', '冬梅绽放',
            
            // 浪浪山时辰系列
            '晨曦初照', '朝阳东升', '正午烈日', '午后斜阳', '黄昏夕照', '夜幕降临', '月圆之夜', '星光满天',
            '破晓时分', '日出东方', '艳阳高照', '夕阳西下', '月上柳梢', '夜深人静', '鸡鸣破晓', '晨钟暮鼓'
        ];
        
        const randomName = langlangshanNames[Math.floor(Math.random() * langlangshanNames.length)];
        this.elements.nameInput.value = randomName;
    }

    setupFullscreenControls() {
        // 监听全屏状态变化
        document.addEventListener('fullscreenchange', () => {
            this.handleFullscreenChange();
        });
        
        document.addEventListener('webkitfullscreenchange', () => {
            this.handleFullscreenChange();
        });
        
        document.addEventListener('mozfullscreenchange', () => {
            this.handleFullscreenChange();
        });
        
        document.addEventListener('MSFullscreenChange', () => {
            this.handleFullscreenChange();
        });
        
        // 启动全屏状态信息更新
        this.startFullscreenStatusUpdate();
    }
    
    startFullscreenStatusUpdate() {
        setInterval(() => {
            this.updateFullscreenGameStatus();
        }, 1000);
    }
    
    updateFullscreenGameStatus() {
        const gameTimeElement = document.getElementById('gameTime');
        const onlinePlayersElement = document.getElementById('onlinePlayers');
        
        if (gameTimeElement && this.gameStartTime) {
            const elapsed = Math.floor((Date.now() - this.gameStartTime) / 1000);
            const minutes = Math.floor(elapsed / 60);
            const seconds = elapsed % 60;
            gameTimeElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
        
        if (onlinePlayersElement) {
            const playerCount = this.gameState.players ? this.gameState.players.length : 0;
            onlinePlayersElement.textContent = playerCount;
        }
    }
    
    // 统一的全屏解决方案 - 适配不同设备
    toggleFullscreen(element) {
        if (!this.isFullscreenActive()) {
            this.enterFullscreen(element);
        } else {
            this.exitFullscreen();
        }
    }
    
    // 检查是否处于全屏状态
    isFullscreenActive() {
        return !!(document.fullscreenElement || 
                 document.webkitFullscreenElement || 
                 document.mozFullScreenElement || 
                 document.msFullscreenElement);
    }
    
    // 进入全屏模式 - 针对不同设备优化
    enterFullscreen(element) {
        // 移动设备特殊处理
        if (this.isMobile) {
            // 尝试锁定屏幕方向为横屏
            this.requestLandscapeOrientation();
            
            // 隐藏地址栏和工具栏（移动浏览器）
            if (window.screen && window.screen.orientation) {
                try {
                    window.screen.orientation.lock('landscape').catch(() => {
                        // 忽略锁定失败的错误
                    });
                } catch (e) {
                    // 忽略不支持的浏览器
                }
            }
        }
        
        // 标准全屏API调用
        const fullscreenPromise = this.requestFullscreenAPI(element);
        
        if (fullscreenPromise && typeof fullscreenPromise.then === 'function') {
            fullscreenPromise.catch(error => {
                console.warn('全屏请求失败:', error);
                // 如果全屏失败，尝试模拟全屏
                this.simulateFullscreen(element);
            });
        }
    }
    
    // 调用浏览器全屏API
    requestFullscreenAPI(element) {
        if (element.requestFullscreen) {
            return element.requestFullscreen();
        } else if (element.webkitRequestFullscreen) {
            return element.webkitRequestFullscreen();
        } else if (element.mozRequestFullScreen) {
            return element.mozRequestFullScreen();
        } else if (element.msRequestFullscreen) {
            return element.msRequestFullscreen();
        }
        return null;
    }
    
    // 退出全屏模式
    exitFullscreen() {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }
    
    // 模拟全屏（当原生全屏API失败时）
    simulateFullscreen(element) {
        element.style.position = 'fixed';
        element.style.top = '0';
        element.style.left = '0';
        element.style.width = '100vw';
        element.style.height = '100vh';
        element.style.zIndex = '9999';
        element.style.backgroundColor = '#000';
        
        // 隐藏页面滚动条
        document.body.style.overflow = 'hidden';
        
        // 标记为模拟全屏状态
        element.setAttribute('data-simulated-fullscreen', 'true');
        
        // 触发全屏变化处理
        this.handleFullscreenChange();
    }
    

    
    handleFullscreenChange() {
        const canvas = document.getElementById('gameCanvas');
        const gameArea = document.querySelector('.game-area');
        const virtualKeypad = document.getElementById('virtualKeypad');

        const gameInfoPanel = document.querySelector('.game-info-panel');
        const gameLeaderboard = document.querySelector('.game-leaderboard');
        const isFullscreen = this.isFullscreenActive() || 
                           gameArea.getAttribute('data-simulated-fullscreen') === 'true';
        
        if (isFullscreen && canvas && gameArea) {
            // 进入全屏模式，最大化游戏区域
            // 更新画布尺寸
            this.updateCanvasSize();
            
            // 确保游戏区域全屏显示
            gameArea.style.position = 'fixed';
            gameArea.style.top = '0';
            gameArea.style.left = '0';
            gameArea.style.width = '100vw';
            gameArea.style.height = '100vh';
            gameArea.style.backgroundColor = '#000';
            gameArea.style.display = 'flex';
            gameArea.style.justifyContent = 'center';
            gameArea.style.alignItems = 'center';
            gameArea.style.zIndex = '9999';
            
            // 设置画布完全填充屏幕
            canvas.style.position = 'relative';
            canvas.style.zIndex = '1';
            canvas.style.margin = '0';
            canvas.style.display = 'block';
            canvas.style.border = 'none';
            canvas.style.borderRadius = '0';
            canvas.style.boxShadow = 'none';
            canvas.style.width = '100vw';
            canvas.style.height = '100vh';
            canvas.style.objectFit = 'fill';
            

            
            // 将游戏信息面板移到全屏元素内部左上角
            if (gameInfoPanel) {
                if (!gameInfoPanel.originalParent) {
                    gameInfoPanel.originalParent = gameInfoPanel.parentNode;
                }
                gameArea.appendChild(gameInfoPanel);
                gameInfoPanel.style.position = 'absolute';
                gameInfoPanel.style.top = '20px';
                gameInfoPanel.style.left = '20px';
                gameInfoPanel.style.zIndex = '10001';
                gameInfoPanel.style.display = 'block';
            }
            
            // 将排行榜移到全屏元素内部右上角
            if (gameLeaderboard) {
                if (!gameLeaderboard.originalParent) {
                    gameLeaderboard.originalParent = gameLeaderboard.parentNode;
                }
                gameArea.appendChild(gameLeaderboard);
                gameLeaderboard.style.position = 'absolute';
                gameLeaderboard.style.top = '20px';
                gameLeaderboard.style.right = '20px';
                gameLeaderboard.style.zIndex = '10001';
                gameLeaderboard.style.display = 'block';
                gameLeaderboard.style.maxHeight = '300px';
                gameLeaderboard.style.overflow = 'auto';
            }
            
            // 将虚拟键盘移动到全屏元素内部并显示在右下角
            if (virtualKeypad) {
                // 保存原始父元素
                if (!virtualKeypad.originalParent) {
                    virtualKeypad.originalParent = virtualKeypad.parentNode;
                }
                // 移动到游戏区域内
                gameArea.appendChild(virtualKeypad);
                
                virtualKeypad.style.position = 'absolute';
                virtualKeypad.style.bottom = '20px';
                virtualKeypad.style.right = '20px';
                virtualKeypad.style.zIndex = '10000';
                virtualKeypad.style.display = 'block';
            }
            

            
            // 隐藏滚动条
            document.body.style.overflow = 'hidden';
            
        } else if (canvas && gameArea) {
            // 退出全屏模式，恢复原始大小
            canvas.style.position = '';
            canvas.style.zIndex = '';
            canvas.style.margin = '';
            canvas.style.display = '';
            canvas.style.border = '';
            canvas.style.borderRadius = '';
            canvas.style.boxShadow = '';
            canvas.style.width = '';
            canvas.style.height = '';
            canvas.style.objectFit = '';
            
            // 清理模拟全屏状态
            gameArea.removeAttribute('data-simulated-fullscreen');
            
            // 恢复画布原始尺寸
            this.updateCanvasSize();
            
            gameArea.style.position = '';
            gameArea.style.top = '';
            gameArea.style.left = '';
            gameArea.style.width = '';
            gameArea.style.height = '';
            gameArea.style.backgroundColor = '';
            gameArea.style.display = '';
            gameArea.style.flexDirection = '';
            gameArea.style.justifyContent = '';
            gameArea.style.alignItems = '';
            gameArea.style.zIndex = '';
            

            
            // 恢复游戏信息面板到原始位置
            if (gameInfoPanel && gameInfoPanel.originalParent) {
                gameInfoPanel.originalParent.appendChild(gameInfoPanel);
                gameInfoPanel.style.position = '';
                gameInfoPanel.style.top = '';
                gameInfoPanel.style.left = '';
                gameInfoPanel.style.zIndex = '';
                gameInfoPanel.style.display = '';
            }
            
            // 恢复排行榜到原始位置
            if (gameLeaderboard && gameLeaderboard.originalParent) {
                gameLeaderboard.originalParent.appendChild(gameLeaderboard);
                gameLeaderboard.style.position = '';
                gameLeaderboard.style.top = '';
                gameLeaderboard.style.right = '';
                gameLeaderboard.style.zIndex = '';
                gameLeaderboard.style.display = '';
                gameLeaderboard.style.maxHeight = '';
                gameLeaderboard.style.overflow = '';
            }
            
            // 恢复虚拟键盘到原始位置和样式
            if (virtualKeypad && virtualKeypad.originalParent) {
                virtualKeypad.originalParent.appendChild(virtualKeypad);
                virtualKeypad.style.position = '';
                virtualKeypad.style.bottom = '';
                virtualKeypad.style.right = '';
                virtualKeypad.style.zIndex = '';
                virtualKeypad.style.display = '';
            }
            

            
            // 恢复滚动条
            document.body.style.overflow = '';
        }
    }
}

// 初始化游戏
const game = new SnakeGame();

// 游戏渲染循环
function gameLoop() {
    // 游戏渲染在服务器消息中触发
    requestAnimationFrame(gameLoop);
}

gameLoop();

// 页面加载完成后聚焦到名称输入框
window.addEventListener('load', () => {
    document.getElementById('nameInput').focus();
});

window.addEventListener('resize', () => {
    game.updateCanvasSize();
    game.adjustCanvasForMobile();
});

// 防止页面刷新时丢失连接
window.addEventListener('beforeunload', () => {
    if (game.ws) {
        game.ws.close();
    }
});